//
//  MusicDownloadViewController.m
//  wAudioShare
//
//  Created by 赵帅 on 14-2-13.
//  Copyright (c) 2014年 赵帅. All rights reserved.
//

#import "MusicDownloadViewController.h"
#import "MJRefresh.h"
#import "MusicDownloadCell.h"

#define RETRYLIMIT 20

@interface MusicDownloadViewController ()
<MJRefreshBaseViewDelegate,serviceGetDownFinishedListDelegate,serviceGetToDownListDelegate,serviceGetDowningStatusDelegate,MusicDownloadCellDelegate,serviceSetDownCmdDelegate,serviceDelDownloadItemDelegate,serviceSetNewImDownUriDelegate>
{
    MJRefreshHeaderView *_header;
    MJRefreshFooterView *_footer;
    
    NSMutableArray * toDownloadArray;
    int toDownloadPage;
    
    NSMutableArray * downFinishedArray;
    int downloadFinishPage;

    int currentClass;
    
    BOOL isServiceGetting;
    
    //当前正在下载的项
    NSDictionary * currentDownloadDic;
    NSTimer * statusTimer;
}

@property (assign) IBOutlet UISegmentedControl * segmentControl;
@property (assign) IBOutlet UITableView * tableView;
@property (assign) IBOutlet UILabel * infoLabel;
@property (assign) IBOutlet UIButton * downloadButton;
@property (assign) IBOutlet UIProgressView * progressView;
@property (assign) IBOutlet UIButton * deleteButton;
@property (assign) IBOutlet UIButton * cleanButton;

@end

@implementation MusicDownloadViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    isServiceGetting = NO;
    
    _header = [MJRefreshHeaderView header];
    _header.scrollView = self.tableView;
    _header.delegate = self;
    
    _footer = [MJRefreshFooterView footer];
    _footer.scrollView = self.tableView;
    _footer.delegate = self;
    
    //清空列表
    UIImage *normalImage = [UIImage imageNamed:@"normalbutton_normal.png"];
    UIEdgeInsets insets = UIEdgeInsetsMake(20, 10, 10, 10);
    normalImage = [normalImage resizableImageWithCapInsets:insets];
    [_cleanButton setBackgroundImage:normalImage forState:UIControlStateNormal];
    
    UIImage *pressImage = [UIImage imageNamed:@"normalbutton_press.png"];
    insets = UIEdgeInsetsMake(20, 10, 10, 10);
    pressImage = [pressImage resizableImageWithCapInsets:insets];
    [_cleanButton setBackgroundImage:pressImage forState:UIControlStateHighlighted];
    
    [_cleanButton setTitle:NSLocalizedString(@"MUSICDOWN_CLEANLIST", @"") forState:UIControlStateNormal];
    
    //segment
    [_segmentControl setTitle:NSLocalizedString(@"MUSICDOWN_TODOWN", @"") forSegmentAtIndex:0];
    [_segmentControl setTitle:NSLocalizedString(@"MUSICDOWN_DOWNFINISH", @"") forSegmentAtIndex:1];
    
    [self getToDownloadList:0];
    
    toDownloadArray = [NSMutableArray array];
    toDownloadPage = 0;
    
    downFinishedArray = [NSMutableArray array];
    downloadFinishPage = 0;
    
    //timer
    statusTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(timerMethod) userInfo:nil repeats:YES];
    
    [[NSRunLoop currentRunLoop] addTimer:statusTimer forMode:NSDefaultRunLoopMode];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newDownloadAdded) name:@"ADDNEWMUSICDOWN" object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - navigation methods
-(NSString *)navigationBarTitle
{
    return NSLocalizedString(@"MUSICDOWN_CONTROL_TITLE",@"");
}

-(BOOL)isNewVersionButtonEnabled
{
    return YES;
}

#pragma mark - IBAction methods
-(IBAction)segmentValueChanged:(UISegmentedControl *)Seg
{
    if(isServiceGetting == YES)
    {
        return;
    }

    int index = Seg.selectedSegmentIndex;
    currentClass = index;
    
    if(index == 0)
    {
        if([toDownloadArray count] == 0)
        {
            [self getToDownloadList:0];
            toDownloadPage = 0;
        }
    }
    else
    {
        if([downFinishedArray count] == 0)
        {
            [self getDownloadFinishList:0];
            downloadFinishPage = 0;
        }
    }
    
    [self.tableView reloadData];
}

-(IBAction)deleteCurrentPressed:(id)sender
{
    [[GlobalService sharedInstance] setDownloadCmd:self cmd:@"del"];
}

-(IBAction)downloadButtonPressed:(id)sender
{
    if([currentDownloadDic[@"state"] intValue] == 1)
    {
        [[GlobalService sharedInstance] setDownloadCmd:self cmd:@"stop"];
    }
    else
    {
        [[GlobalService sharedInstance] setDownloadCmd:self cmd:@"start"];
    }
}

-(IBAction)cleanButtonPressed:(id)sender
{
    NSString * noteStr = nil;
    if(currentClass == 0)
    {
        noteStr = NSLocalizedString(@"MUSICDOWN_CLEANTODOWN_NOTE", @"");
    }
    else
    {
        noteStr = NSLocalizedString(@"MUSICDOWN_CLEANDOWNFINISH_NOTE", @"");
    }
    
    UIAlertView * av = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"ALERT_TITLE", @"") message:noteStr delegate:self cancelButtonTitle:NSLocalizedString(@"CANCEL", @"") otherButtonTitles:NSLocalizedString(@"MUSICDOWN_DELETEFILE_NOTE", @""),NSLocalizedString(@"MUSICDOWN_CLEANONLYLIST_NOTE", @""), nil];
    [av show];
}

#pragma mark -
#pragma mark UITableView Delegate & Datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    int number = 0;
    for(NSArray * arr  in [self getCurrentArray])
    {
        number+=[arr count];
    }
    
    return number;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MusicDownloadCell *cell = (MusicDownloadCell *)[tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell =  [[[NSBundle mainBundle] loadNibNamed:@"MusicDownloadCell" owner:self options:nil] objectAtIndex:0];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    
    NSMutableArray * pagearray = [self getCurrentArray];
    NSMutableArray * array = pagearray[indexPath.row/10];
    int indexInPage = indexPath.row%10;
    
    NSDictionary * dic = array[indexInPage];
    // Configure the cell
    
    cell.downloadURI = dic[@"uri"];
    
    if(currentClass == 1)
    {
        cell.actionButton.hidden = YES;
    }
    
    [cell.actionButton setBackgroundImage:[UIImage imageNamed:@"wait_icon"] forState:UIControlStateNormal];
    
    if([dic[@"savename"] length] != 0)
    {
        cell.titleLabel.text = array[indexInPage][@"savename"];
    }
    else
    {
        NSArray * arr = [array[indexInPage][@"uri"] componentsSeparatedByString:@"/"];
        
        if([[arr lastObject] length] != 0)
        {
            cell.titleLabel.text = [arr lastObject];
        }
        else
        {
            cell.titleLabel.text = array[indexInPage][@"uri"];
        }
    }
    
    if(currentClass == 1)//已下载
    {
        
    }
    else//未下载
    {
        if([currentDownloadDic[@"percent"] intValue] > 0)
        {
            if([dic[@"uri"] isEqualToString:currentDownloadDic[@"uri"]])
            {
                [cell.actionButton setBackgroundImage:[UIImage imageNamed:@"MusicDownload"] forState:UIControlStateNormal];
            }
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
    
}

#pragma mark - MJRefreshBaseViewDelegate method
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    if(isServiceGetting == YES) return;
    
    if(refreshView == _header)
    {
        [[self getCurrentArray] removeAllObjects];
        [self.tableView reloadData];
        
        if(currentClass == 0)
        {
            [self getToDownloadList:0];
            toDownloadPage = 0;
        }
        else
        {
            [self getDownloadFinishList:0];
            downloadFinishPage = 0;
        }
    }
    else if(refreshView == _footer)
    {
        //从最后一页开始更新 更新到下一页
        if(currentClass == 0)
        {
            [self getToDownloadList:toDownloadPage++];
        }
        else
        {
            [self getDownloadFinishList:downloadFinishPage++];
        }
    }
}

#pragma mark - private methods
-(NSMutableArray *)getCurrentArray
{
    NSMutableArray * array;
    
    if(currentClass == 0)
    {
        array = toDownloadArray;
    }
    else
    {
        array = downFinishedArray;
    }
    
    return array;
}

-(void)timerMethod
{
    [[GlobalService sharedInstance] getDownloadingStatus:self];
}

-(void)stopAllTimers
{
    if(statusTimer != nil && [statusTimer isValid])
    {
        [statusTimer invalidate];
        statusTimer = nil;
    }
}

-(void)getToDownloadList:(int)page
{
    isServiceGetting = YES;
    
    [[GlobalService sharedInstance] removeHandler:self];
    [[GlobalService sharedInstance] getToDownloadList:self page:page];
}

-(void)getDownloadFinishList:(int)page
{
    isServiceGetting = YES;
    
    [[GlobalService sharedInstance] removeHandler:self];
    [[GlobalService sharedInstance] getDownFinishedList:self page:page];
}

-(void)checkIfNeedDelete
{
    int firstDeleteIndexInPage = -1;
    for(int i=0;i<[toDownloadArray count];i++)
    {
        NSMutableArray * arr = toDownloadArray[i];
        for(NSDictionary * dic in arr)
        {
            if([dic[@"downtimes"] intValue] > 20)
            {
                if(firstDeleteIndexInPage == -1)
                {
                    firstDeleteIndexInPage = i;
                }
                
                [[GlobalService sharedInstance] deleteDownloadItem:self listIndex:0 controlFlag:[[GlobalInfo sharedInstance] isMusicDeleteFile]?1:0 uri:dic[@"uri"]];
            }
        }
    }
    
    if(firstDeleteIndexInPage != -1)
    {
        double delayInSeconds = 0.5;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self getToDownloadList:firstDeleteIndexInPage];
        });
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    int controlFlag = 0;
    
    if(buttonIndex == 1)//删除文件
    {
        controlFlag = 1;
    }
    else if(buttonIndex == 2)//不删除文件
    {
        controlFlag = 0;
    }
    
    [[self getCurrentArray] removeAllObjects];
    [self.tableView reloadData];
    
    [[GlobalService sharedInstance] deleteDownloadItem:self listIndex:currentClass controlFlag:controlFlag uri:@""];
    
    double delayInSeconds = 0.5;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self getToDownloadList:0];
    });
}

-(void)newDownloadAdded
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [[self getCurrentArray] removeAllObjects];
        [self.tableView reloadData];
        [self getToDownloadList:0];
    });
}

#pragma mark - MusicDownloadCellDelegate methods
-(void)actionButtonPressed:(NSString *)uri
{
    NSLog(@"action %@",uri);
    if(![uri isEqualToString:currentDownloadDic[@"uri"]])
    {
        if([currentDownloadDic[@"state"] intValue] == 0)
        {
            [[GlobalService sharedInstance] setDownloadCmd:self cmd:@"start"];
        }

        [[GlobalService sharedInstance] setImNewDownUri:self uri:uri];
    }
}

-(void)deleteButtonPressed:(NSString *)uri
{
    int listIndex = currentClass;

    [[GlobalService sharedInstance] deleteDownloadItem:self listIndex:listIndex controlFlag:[[GlobalInfo sharedInstance] isMusicDeleteFile]?1:0 uri:uri];
}

#pragma mark - service methods
-(void)serviceGetToDownListCallBack:(NSDictionary*)dicCallBack
{
    NSLog(@"serviceGetToDownListCallBack %@",dicCallBack);
    [_header endRefreshing];
    [_footer endRefreshing];
    
    if(dicCallBack == nil || [[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_FAIL intValue])
    {
        if([dicCallBack[@"message"] isEqualToString:@"USB not ready"])
        {
            [self.view makeToast:NSLocalizedString(@"MUSICDOWN_NEEDUSB", @"")
                        duration:3.0
                        position:@"bottom"
                           title:NSLocalizedString(@"ALERT_TITLE",@"")];
        }
    }
    else if([[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_CONNECTIONFAIL intValue] || [[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_TIMEOUT intValue])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PopTabBarController" object:self];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ErrorComeBack" object:nil];
    }
    
    if([dicCallBack[@"toDownList"] count] == 0)
    {
        isServiceGetting = NO;
        int count =[toDownloadArray count];
        toDownloadPage = count-1>0?count-1:0;
        
        for(int i=[dicCallBack[@"page"] intValue];i<count;i++)
        {
            [toDownloadArray removeObjectAtIndex:i];
        }
        
        [self checkIfNeedDelete];
        
        if(currentClass == 0)
        {
            [self.tableView reloadData];
        }
        
        return;
    }
    
    NSMutableArray * array = [NSMutableArray arrayWithArray:dicCallBack[@"toDownList"]];
    
    if([dicCallBack[@"page"] intValue] < [toDownloadArray count])
    {
        [toDownloadArray replaceObjectAtIndex:[dicCallBack[@"page"] intValue] withObject:array];
    }
    else
    {
        [toDownloadArray addObject:array];
    }

    if(currentClass == 0)
    {
        [self.tableView reloadData];
    }
    
    if([dicCallBack[@"page"] intValue] < toDownloadPage)
    {
        [self getToDownloadList:([dicCallBack[@"page"] intValue]+1)];
    }
    else if([dicCallBack[@"page"] intValue] == toDownloadPage)
    {
        isServiceGetting = NO;
        
        [self checkIfNeedDelete];
    }
}

-(void)serviceGetDownFinishedListCallBack:(NSDictionary*)dicCallBack
{
    NSLog(@"serviceGetDownFinishedListCallBack %@",dicCallBack);
    
    [_header endRefreshing];
    [_footer endRefreshing];
   
    if(dicCallBack == nil || [[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_FAIL intValue])
    {
        if([dicCallBack[@"message"] isEqualToString:@"USB not ready"])
        {
            [self.view makeToast:NSLocalizedString(@"MUSICDOWN_NEEDUSB", @"")
                        duration:3.0
                        position:@"bottom"
                           title:NSLocalizedString(@"ALERT_TITLE",@"")];
        }
    }
    else if([[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_CONNECTIONFAIL intValue] || [[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_TIMEOUT intValue])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PopTabBarController" object:self];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ErrorComeBack" object:nil];
    }
    
    if([dicCallBack[@"downFinishedList"] count] == 0)
    {
        isServiceGetting = NO;
        int count = [downFinishedArray count];
        downloadFinishPage = count-1>0?count-1:0;
        
        for(int i=[dicCallBack[@"page"] intValue];i<count;i++)
        {
            [downFinishedArray removeObjectAtIndex:i];
        }
        if(currentClass == 1)
        {
            [self.tableView reloadData];
        }
        
        return;
    }
    
    NSMutableArray * array = [NSMutableArray arrayWithArray:dicCallBack[@"downFinishedList"]];
    if([dicCallBack[@"page"] intValue] < [downFinishedArray count])
    {
        [downFinishedArray replaceObjectAtIndex:[dicCallBack[@"page"] intValue] withObject:array];
    }
    else
    {
        [downFinishedArray addObject:array];
    }

    if(currentClass == 1)
    {
        [self.tableView reloadData];
    }
    
    if([dicCallBack[@"page"] intValue] < downloadFinishPage)
    {
        [self getDownloadFinishList:([dicCallBack[@"page"] intValue]+1)];
    }
    else if([dicCallBack[@"page"] intValue] == downloadFinishPage)
    {
        isServiceGetting = NO;
    }
}

-(void)serviceGetDowningStatusCallBack:(NSDictionary*)dicCallBack
{
    if(dicCallBack == nil || [[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_FAIL intValue])
    {
        return;
    }
    else if([[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_CONNECTIONFAIL intValue] || [[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_TIMEOUT intValue])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PopTabBarController" object:self];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ErrorComeBack" object:nil];
    }
    
    currentDownloadDic = dicCallBack;
    
    BOOL isExsit = NO;
    for(NSArray * arr in toDownloadArray)
    {
        for(NSDictionary * dic in arr)
        {
            if([dic[@"uri"] isEqualToString:currentDownloadDic[@"uri"]])
            {
                isExsit = YES;
                break;
            }
        }
    }
    
    if([dicCallBack[@"state"] intValue] == 0)
    {
        [_downloadButton setBackgroundImage:[UIImage imageNamed:@"playbutton_normal"] forState:UIControlStateNormal];
    }
    else
    {
        [_downloadButton setBackgroundImage:[UIImage imageNamed:@"pausebutton_normal"] forState:UIControlStateNormal];
    }
    
    if([currentDownloadDic[@"percent"] intValue] < 0)
    {
        _infoLabel.text = NSLocalizedString(@"MUSICDOWN_NODOWLOADING", @"");
        [self.progressView setProgress:0 animated:YES];
        _deleteButton.enabled = NO;
        
        return;
    }
    
    if([dicCallBack[@"savename"] length] == 0)
    {
        _infoLabel.text = NSLocalizedString(@"MUSICDOWN_NODOWLOADING", @"");
        _deleteButton.enabled = NO;
        [self.progressView setProgress:0 animated:YES];

        if(currentClass == 0)
        {
            if([currentDownloadDic[@"percent"] intValue] == 100 && isExsit == YES)
            {
                _infoLabel.text = NSLocalizedString(@"MUSICDOWN_DOWNLOADFINISH", @"");
                
                [[self getCurrentArray] removeAllObjects];
                [self.tableView reloadData];
                [self getToDownloadList:0];
            }
        }
    }
    else if([currentDownloadDic[@"percent"] intValue] > 0)
    {
        _infoLabel.text = [NSString stringWithFormat:@"%@：%@",NSLocalizedString(@"MUSICDOWN_CURRENTMISSION",@""), dicCallBack[@"savename"]];
        _deleteButton.enabled = YES;
        
        [self.progressView setProgress:[currentDownloadDic[@"percent"] intValue]/100.0 animated:YES];
        
        if(isExsit == NO)
        {
            if(currentClass == 0)
            {
                [[self getCurrentArray] removeAllObjects];
                [self.tableView reloadData];
                [self getToDownloadList:0];
            }
        }
        else
        {
            [self.tableView reloadData];
        }
    }
}

-(void)serviceSetDownCmdCallBack:(NSDictionary*)dicCallBack
{
    if(dicCallBack == nil || [[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_FAIL intValue])
    {
        return;
    }
    else if([[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_CONNECTIONFAIL intValue] || [[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_TIMEOUT intValue])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PopTabBarController" object:self];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ErrorComeBack" object:nil];
    }
    
    [[self getCurrentArray] removeAllObjects];
    [self.tableView reloadData];
    
    if(currentClass == 0)
    {
        [self getToDownloadList:0];
    }
    else
    {
        [self getDownloadFinishList:0];
    }
}

-(void)serviceDelDownloadItemCallBack:(NSDictionary*)dicCallBack
{
    if(dicCallBack == nil || [[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_FAIL intValue])
    {
        return;
    }
    else if([[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_CONNECTIONFAIL intValue] || [[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_TIMEOUT intValue])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PopTabBarController" object:self];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ErrorComeBack" object:nil];
    }
    
    [[self getCurrentArray] removeAllObjects];
    [self.tableView reloadData];
    
    if(currentClass == 0)
    {
        [self getToDownloadList:0];
    }
    else
    {
        [self getDownloadFinishList:0];
    }
}

-(void)serviceSetNewImDownUriCallBack:(NSDictionary*)dicCallBack
{
    if(dicCallBack == nil || [[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_FAIL intValue])
    {
        
        
        return;
    }
    else if([[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_CONNECTIONFAIL intValue] || [[dicCallBack objectForKey:@"responsestatus"] intValue] == [SERVICE_TIMEOUT intValue])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PopTabBarController" object:self];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ErrorComeBack" object:nil];
    }
    NSLog(@"serviceSetNewImDownUriCallBack: %@",dicCallBack);
    [self.tableView reloadData];
}

@end
